<?php


class handleCoupon extends IController
{
    private $limit = 500;
    private $logObj;


    public function init()
    {
        $this->logObj = new Log('file');
    }

    /**
     * 开始处理创建优惠券
     */
    public function create()
    {
        $queue_name     = "handel_coupon_queue";
        $redis_obj      = new redisMq();
        $message_length = $redis_obj->getMessageLength($queue_name);
        if ($redis_obj->hasError()) {
            $this->logObj->cliWrite('error', array("读取redis队列失败：" . var_export($redis_obj->getError(), true)));
            exit;
        }
        if (empty($message_length)) {
            exit;
        }
        //可以配置每次消费几条
        for ($i = 0; $i < $this->limit; $i++) {
            $result = $redis_obj->pop($queue_name);
            //如果发生异常
            if ($redis_obj->hasError()) {
                $this->logObj->cliWrite('error', array("读取redis队列失败：" . var_export($redis_obj->getError(), true)));
                exit;
            }
            //有内容的时候则进行处理
            if ($result['msg_id']) {
                $data = json_decode($result['msg_body'], true);
                //进行功能逻辑处理
                if ($data) {
                    $couponData = array(
                        'coupon_group_id' => $data['coupon_group_id'],
                        'code'            => $data['code'],
                        'send_type'       => $data['send_type'],
                        'create_time'     => $data['create_time'],
                        'use_type'        => $data['use_type'],
                    );
                    $couponDb   = new IModel('coupon');
                    $couponDb->setData($couponData);
                    $couponId = $couponDb->add();
                    if ($couponId === false) {
                        $this->logObj->cliWrite('error', array("优惠券生成失败！" . var_export($couponData, true)));
                    }
                }
                $redis_obj->remove($queue_name, $result['msg_id']);;
            } else {
                break;
            }
        }

    }

    /**
     * 检测优惠券过期
     */
    public function check()
    {
        $couponGroupsDb   = new IModel('coupon_groups');
        $nowDate          = ITime::getTime();
        $where            = "status = 1";
        $couponGroupsInfo = $couponGroupsDb->query($where, 'id,end_time,prop_sale,goods_sale,seller_id');
        if ($couponGroupsInfo) {
            $couponDb = new IModel('coupon');
            foreach ($couponGroupsInfo as $c_val) {
                if (strtotime($c_val['end_time']) < $nowDate) {
                    $couponWhere = "coupon_group_id ={$c_val['id']} and status in(1,2)";
                    $couponDb->setData(array('status' => 4));
                    $couponDb->update($couponWhere);
                    if ($c_val['goods_sale'] == 1) {
                        $goodsDb = new IModel('goods');
                        $goodsDb->setData(array(
                            'is_del'    => 2,
                            'down_time' => ITime::getDateTime()
                        ));
                        $goodsDb->update("coupon_group_id=" . $c_val['id']);
                    }
                    if ($c_val['prop_sale'] == 1) {
                        $couponPropsDb  = new IModel('coupon_props');
                        $couponPropsRes = $couponPropsDb->query("coupon_group_id={$c_val['id']}");
                        if ($couponPropsRes) {
                            $sellerDb = new IModel('seller');
                            $zxlObj   = new  zxlhelper();
                            foreach ($couponPropsRes as $pros_val) {
                                $selleResult       = $sellerDb->getObj("id ={$pros_val['seller_id']}");
                                $tenantTokenResult = SystemToken::getTenantTokenList(array($selleResult['seller_name']));
                                $token             = $tenantTokenResult['success'][$selleResult['seller_name']];
                                if ($tenantTokenResult['failure']) {
                                    $this->logObj->Write('error', array("{$selleResult['seller_name']} 编辑时优惠券 ，同步道具租户获取Token失败，：" . explode(',', $tenantTokenResult['failure'])));
                                    continue;
                                }
                                $propData      = array(
                                    'coupon_props_id' => $pros_val['props_id'],
                                    'token'           => rawurldecode($token),
                                );
                                $addPropResult = $zxlObj->setCouponExpireStop($propData);
                                if ($addPropResult === false) {
                                    $this->logObj->cliWrite('error', array("优惠过期,强制结束失败！同步关闭道具失败"));
                                }
                            }
                        }
                    }
                    $couponGroupsDb->setData(array(
                        'status'      => 2,
                        'update_time' => ITime::getDateTime()
                    ));
                    $couponGroupsDb->update("id=" . $c_val['id']);
                    //优惠卷过期清空优惠卷列表
                    $redisObj = new IRedisCache();
                    //获取redis实例
                    $cache = $redisObj->r('shop');
                    //获取redis配置的key
                    $key = $redisObj->redis_key('coupon_list');
                    $cache->zRem($key, $c_val['id']);
                }
            }
        }
    }

    /**
     * 优惠券到期提醒
     *
     */
    public function checkExpireSendMessage()
    {

        $redisObj = new IRedisCache();
        //获取redis实例
        $cache = $redisObj->r('shop');
        //获取redis配置的key
        $redis_key = $redisObj->redis_key('coupon_list');
        $data      = $cache->zRangeByScore($redis_key, '-inf', '+inf', array('withscores' => true));
        if ($data) {
            $mallHost     = IWeb::$app->config['mall_host'];
            $config       = IWeb::$app->config['check_coupon_expire_date'];
            $expireConfig = 60 * 60 * $config;
            $couponUserDb = new IQuery('coupon_user as cu');
            $nowDate      = ITime::getTime();
            foreach ($data as $key => $value) {
                if (intval($value - $nowDate) == $expireConfig) {
                    $this->logObj->cliWrite('operation', array('开始处理，优惠券过期提醒推送消息，优惠券主id:' . "{$key}"));
                    $couponUserDb->where  = "cu.coupon_group_id={$key} and cu.is_used=0";
                    $couponUserDb->fields = "cu.user_id,cg.name";
                    $couponUserDb->join   = "left join coupon_groups as cg on cg.id=cu.coupon_group_id";
                    $data                 = $couponUserDb->find();
                    foreach ($data as $user_val) {
                        $this->logObj->cliWrite('operation', array('开始处理，优惠券过期提醒推送消息，优惠券主id:' . "{$key}" . "用户id：{$user_val['user_id']}"));
                        $userModel           = new IModel('user');
                        $userInfo            = $userModel->getObj('id = ' . $user_val['user_id']);
                        $userNameSplitResult = explode('@', $userInfo['username']);
                        $userName            = $userNameSplitResult[0];
                        $tenantId            = $userNameSplitResult[1];
                        $tenantTokenResult   = SystemToken::getTenantTokenList(array($tenantId));
                        if ($tenantTokenResult['failure']) {
                            $this->logObj->cliWrite('error', array('以下租户获取Token失败，优惠券过期提醒推送消息失败：' . explode(',', $tenantTokenResult['failure']) . "优惠券主id:{$key}，用户信息user_id:{$user_val['user_id']}"));
                            continue;
                        }
                        $messageParams = array(
                            'receive_type'          => 0,
                            'message_kind'          => 17,
                            'message_content'       => json_encode(array(
                                'content'      => '您有优惠券即将过期，赶紧去积分商城用掉吧！',
                                'coupon_title' => $user_val['name'],
                                'url'          => $mallHost . 'coupons/user_coupon_list'
                            ), JSON_UNESCAPED_UNICODE),
                            'message_content_brief' => '您有优惠券即将过期',
                            'user_ids'              => $userName,
                            'token'                 => rawurldecode($tenantTokenResult['success'][$tenantId]),
                        );
                        $this->logObj->cliWrite('operation', array(var_export($messageParams, true)));
                        ZXLHelper::sendSystemMessage($messageParams);
                    }
                    $cache->zRem($redis_key, $key);
                }
            }
        }
    }

}